package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.dao.SocialSecurityPayDetailDao;
import io.renren.entity.*;
import io.renren.utils.RRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.dao.SocialsbSummaryDao;
import io.renren.service.SocialsbSummaryService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Transactional(propagation= Propagation.REQUIRED)
@Service("socialsbSummaryService")
public class SocialsbSummaryServiceImpl implements SocialsbSummaryService {

	/**
	 * 日志对象
	 */
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SocialsbSummaryDao socialsbSummaryDao;
	@Autowired
	private SocialSecurityPayDetailDao socialSecurityPayDetailDao;

	@Override
	public SocialsbSummaryEntity queryObject(Integer id){
		return socialsbSummaryDao.queryObject(id);
	}
	
	@Override
	public List<SocialsbSummaryEntity> queryList(Map<String, Object> map){
		return socialsbSummaryDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return socialsbSummaryDao.queryTotal(map);
	}
	
	@Override
	public void save(SocialsbSummaryEntity socialsbSummary){
		socialsbSummaryDao.save(socialsbSummary);
	}

	@Override
	public void update(SocialsbSummaryEntity socialsbSummary){
		socialsbSummaryDao.update(socialsbSummary);
	}
	
	@Override
	public void delete(Integer id){
		socialsbSummaryDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		for(int i=0;i<ids.length;i++){
			SocialsbSummaryEntity socialsbSummaryEntity = queryObject(ids[i]);
			SocialSecurityPayDetailEntity socialSecurityPayDetailEntity = new SocialSecurityPayDetailEntity();
			socialSecurityPayDetailEntity.setId(socialsbSummaryEntity.getDetailid());
			socialSecurityPayDetailEntity.setPayState("0");
			socialSecurityPayDetailDao.update(socialSecurityPayDetailEntity);
		}
		socialsbSummaryDao.deleteBatch(ids);
	}

	@Override
	public Map<String,Object> insertSocial(JSONObject params, SysUserEntity sysUserEntity) {
		try {
			int month=0,year=0;
			String insuredtype = params.get("insuredtype").toString();
			SocialSecurityPayDetailEntity socialSecurityPayDetailEntity = new SocialSecurityPayDetailEntity();
			if (!"".equals(params.get("month").toString())&&!"01".equals(params.get("month").toString())) {
				socialSecurityPayDetailEntity.setMonth(Integer.parseInt(params.get("month").toString()));
				year=Integer.parseInt(params.get("year").toString());
				month=Integer.parseInt(params.get("month").toString())-1;//获取上一个月
			}else if("01".equals(params.get("month").toString())){//如果月份是1月份  上一个月就去年的12月份
				year =Integer.parseInt(params.get("year").toString())-1;
				month=12;
			} else {
				throw new RRException("未选择月份！");
			}
			if (!"".equals(params.get("year").toString())) {
				socialSecurityPayDetailEntity.setYear(Integer.parseInt(params.get("year").toString()));
			} else {
				throw new RRException("未选择年份！");
			}
			if (!"".equals(params.get("insuredtype").toString())) {
				socialSecurityPayDetailEntity.setSocialSecurityType(params.get("insuredtype").toString());
			} else {
				throw new RRException("未选保险类型！");
			}

				//生成批次号
				String batchcode =params.get("year").toString()+"_"+params.get("month").toString()+"_"+params.get("insuredtype").toString();
			//获取生成数据
				List<SocialSecurityPayDetailEntity> socialSecurityPayDetailEntityList = socialSecurityPayDetailDao.getSocialSecurityPayDetailEntity(socialSecurityPayDetailEntity);
				if (socialSecurityPayDetailEntityList.size() == 0) {
					throw new RRException("生成失败,未找到匹配的数据!");
				}
				for (SocialSecurityPayDetailEntity list : socialSecurityPayDetailEntityList) {
					SocialsbSummaryEntity socialsbSummaryEntity = new SocialsbSummaryEntity();
					socialsbSummaryEntity.setDetailid(list.getId());//社保缴付明细id
					socialsbSummaryEntity.setBatchcode(batchcode);
					socialsbSummaryEntity.setInsuredtype(list.getSocialSecurityType());
					socialsbSummaryEntity.setUsername(list.getName());
					socialsbSummaryEntity.setUnitid(list.getUnitId());
					socialsbSummaryEntity.setUnitname(list.getUnitName());
					socialsbSummaryEntity.setIdentitynumber(list.getCardNo());
					socialsbSummaryEntity.setActualsettlemonth(list.getMonth());
					socialsbSummaryEntity.setActualsettleyear(list.getYear());
					socialsbSummaryEntity.setAmountpayableunit(list.getUnitPayable());
					socialsbSummaryEntity.setIndividualamountpay(list.getPersonPayable());
					socialsbSummaryEntity.setInstastatus("0");
					//合计费用
					if(list.getUnitPayable()!=null&&list.getPersonPayable()!=null){
						socialsbSummaryEntity.setTotalcost(list.getUnitPayable()+list.getPersonPayable());
					}
					//未完
					socialsbSummaryEntity.setUnitinsuredratio(list.getUnitScale());
					socialsbSummaryEntity.setPersoninsurratio(list.getPersonScale());

					socialsbSummaryEntity.setRepairunit(list.getBubaoPayableUnit());
					socialsbSummaryEntity.setRepairperson(list.getBubaoPayablePerson());
					//补报金额小计
					if(list.getBubaoPayableUnit()!=null&&list.getBubaoPayablePerson()!=null){
						socialsbSummaryEntity.setRepairsum(list.getBubaoPayableUnit()+list.getBubaoPayablePerson());
					}

					socialsbSummaryEntity.setBasechangeunit(list.getBalancePayableUnit());
					socialsbSummaryEntity.setBasechangeperson(list.getBalancePayablePerson());
					//补差金额小计
					if(list.getBalancePayableUnit()!=null&&list.getBalancePayablePerson()!=null){
						socialsbSummaryEntity.setBasechangesum(list.getBalancePayableUnit()+list.getBalancePayablePerson());
					}
					socialsbSummaryEntity.setUnitpay(list.getUnitPayable());
					socialsbSummaryEntity.setPersonpay(list.getPersonPayable());
					//小计实付金额
					if(list.getUnitPayable()!=null&&list.getPersonPayable()!=null){
						socialsbSummaryEntity.setPaysum(list.getUnitPayable()+list.getPersonPayable());
					}
					socialsbSummaryDao.save(socialsbSummaryEntity);
					if(list.getUnitPayable()>0||list.getBubaoPayableUnit()>0||list.getBalancePayableUnit()>0){
						socialSecurityPayDetailDao.updateSocialSecurityPayDetailEntity(list);
					}else{
						throw new RRException("单位应缴，补报，补差金额应大于0，修改社保缴付明细状态失败!");
					}

				}
				return getMapEntity(params.get("year").toString(),params.get("month").toString(),params.get("insuredtype").toString(),year,month);
			//处理合计字段业务开始------------------------------------------结束
			}catch (RRException e) {
			logger.info("e",e);
				throw e;
			}
	}

	public Map<String,Object> getMapEntity(String year,String month,String insuredtype,int tempyear,int tempmonth) {
		try{
			//处理合计字段业务开始------------------------------------------
			SocialSecurityPayDetailEntity socialSecurityPayDetailEntity = new SocialSecurityPayDetailEntity();
			socialSecurityPayDetailEntity.setMonth(Integer.parseInt(month));
			socialSecurityPayDetailEntity.setYear(Integer.parseInt(year));
			socialSecurityPayDetailEntity.setSocialSecurityType(insuredtype);
			Map<String,Object> map = new HashMap<String,Object>();
			//本月实际参保人数
			int thismactual =socialSecurityPayDetailDao.getSocialSecurityPayDetailEntityCount(socialSecurityPayDetailEntity);
			map.put("thismactual",thismactual);
			//本月缴费基数之和
			int paymentbasesum =socialSecurityPayDetailDao.getSocialSecurityPayDetailEntitySum(socialSecurityPayDetailEntity);
			map.put("paymentbasesum",paymentbasesum);
			//本月人均缴费基数
			int paymentbase;
			if(thismactual==0){
				paymentbase = 0;
			}else{
				paymentbase = paymentbasesum/thismactual;
			}
			map.put("paymentbase",paymentbase);
			//获取本月新增人数
			SocialSecurityTransactionEntity socialSecurityTransactionEntity = new SocialSecurityTransactionEntity();
			//时间转换
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date date = format.parse(year+"-"+month+"-01");
			//获取新增人数
			socialSecurityTransactionEntity.setDeclareType("0");
			socialSecurityTransactionEntity.setDeclareDate(date);
			int thismonthadd = socialSecurityPayDetailDao.getSocialSecurityPayDetailEntityPeople(socialSecurityTransactionEntity);
			map.put("thismonthadd",thismonthadd);
			//获取减少人数
			socialSecurityTransactionEntity.setDeclareType("1");
			int thismreduce = socialSecurityPayDetailDao.getSocialSecurityPayDetailEntityPeople(socialSecurityTransactionEntity);
			map.put("thismreduce",thismreduce);
			//上月参保人数
			socialSecurityPayDetailEntity.setYear(tempyear);
			socialSecurityPayDetailEntity.setMonth(tempmonth);
			int lastmpeople = socialSecurityPayDetailDao.getSocialSecurityPayDetailEntityCount(socialSecurityPayDetailEntity);
			map.put("lastmpeople",lastmpeople);
			return map;
		}catch (Exception e) {
			logger.info("e",e);
		}
		return null;
	}
	@Override
	public void simpleAudit(JSONObject params, SysUserEntity sysUserEntity) {
		int count=0;
		try {
			SocialsbSummaryEntity socialsbSummaryEntity = new SocialsbSummaryEntity();
			socialsbSummaryEntity.setId(Integer.parseInt(params.get("id").toString()));
			if("0".equals(params.get("audit").toString())){
				count=1;
			}else if("1".equals(params.get("audit").toString())){
				socialsbSummaryEntity.setInstastatus("0");
				count = socialsbSummaryDao.queryCount(socialsbSummaryEntity);
			}else if("2".equals(params.get("audit").toString())){
				socialsbSummaryEntity.setInstastatus("1");
				count =socialsbSummaryDao.queryCount(socialsbSummaryEntity);
			}else if("3".equals(params.get("audit").toString())){
				socialsbSummaryEntity.setInstastatus("2");
				count =socialsbSummaryDao.queryCount(socialsbSummaryEntity);
			}
			if(count!=1){
				throw new RRException("数据可能已提交，请刷新页面！");
			}
			socialsbSummaryEntity.setInstastatus(params.get("audit").toString());
			socialsbSummaryEntity.setFirstinstaperson(sysUserEntity.getUsername());
			socialsbSummaryEntity.setFirstinstance(new Date());
			socialsbSummaryDao.simpleAudit(socialsbSummaryEntity);
		}catch (RRException e) {
			logger.info("e",e);
			throw e;
		}
	}
}
